package com.n3wax.automation.security.isy;

import com.n3wax.automation.security.ademco.AlarmEventConsumer;
import com.n3wax.automation.security.ademco.AlarmSystemStatus;

import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Vector;


public class IsyConnector implements AlarmEventConsumer {

    private AlarmSystemStatus alarmStatus = null;

    public void alarmActivation(String zoneID) {
        try {
            URL url = new URL("http://192.168.1.8/rest/programs/0009/runThen");
            URLConnection conn = url.openConnection();
            String encoding = new sun.misc.BASE64Encoder().encode("admin:GqNcdod".getBytes());
            conn.setRequestProperty("Authorization", "Basic " + encoding);
            conn.getContent();
        } catch (IOException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
    }

    public void updateAlarmStatus(AlarmSystemStatus statusObj)
    {
        //update zone statuses
        //we need a way to make zone statuses not hardcoded, but we'll hardcode for now
        //update alarm state
        HashMap <String,Boolean> zoneMap = new HashMap<String, Boolean>();
        zoneMap = statusObj.getZoneStatuses();
        Collection zoneStatuses = zoneMap.values();
        Iterator it = zoneStatuses.iterator();
        int c = 1;
        while(it.hasNext())
        {
            String zoneValue = "0";
            Boolean zoneStatus = (Boolean)it.hasNext();
            if(zoneStatus.booleanValue())
            {
                zoneValue = "1";
            }
            else
            {
                zoneValue = "0";
            }

            String url = "http://192.168.1.8/rest/vars/set/2/" + c + "/" + zoneValue;
            makeGetRequest(url, "admin", "GqNcdod");
            c++;
        }

        String zoneValue = String.valueOf(statusObj.alarmStatus);

        String url = "http://192.168.1.8/rest/vars/set/2/17/" + zoneValue;
        makeGetRequest(url, "admin", "GqNcdod");
        System.out.println("Sent update to ISY");
    }

    public void makeGetRequest(String urlString, String username, String password)
    {
         try {
            URL url = new URL(urlString);
            URLConnection conn = url.openConnection();
            String encoding = new sun.misc.BASE64Encoder().encode((username + ":" + password).getBytes());
            conn.setRequestProperty("Authorization", "Basic " + encoding);
            conn.getContent();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public void alarmUpdate(AlarmSystemStatus statusObj) {
        updateAlarmStatus(statusObj);
    }
}
